<template>
  <van-icon
        :color="isCollected?'#ffa500':'#777'"
        :name="isCollected?'star':'star-o'"
        :loading="loading"
        @click="onCollect"
      />
</template>

<script>
import { addCollect, deleteCollect } from '@/api/article'
import { ref } from 'vue'
import { Toast } from 'vant'
export default {
  name: 'CollectArticle',
  props: {
    isCollected: {
      type: Boolean,
      required: true
    },
    articleId: {
      type: [Number, String],
      required: true
    }
  },
  setup (props, context) {
    const loading = ref(false)// 是否处于加载状态
    async function onCollect () {
      loading.value = true
      try {
        if (props.isCollected) {
          // 取消收藏
          await deleteCollect(props.articleId)
          context.emit('deleteCollect')
          Toast('已取消收藏')
        } else {
          // 收藏
          await addCollect(props.articleId)
          context.emit('addCollect')
          Toast('收藏成功')
        }
      } catch (err) {
        if (err.response && err.response.status === 401) {
          Toast('请先登录')
        } else {
          Toast('操作失败')
        }
      }
      loading.value = false
    }
    return {
      loading,
      onCollect
    }
  }
}
</script>

<style>

</style>
